package org.govhack.okcapital.controllers;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.govhack.okcapital.util.FileIOUtil;
import org.govhack.okcapital.view.JSONModelAndView;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

/**
 * Utilities for controllers
 * 
 * @author Josh Vote
 * 
 */
public class BaseController {
    /**
     * Generates a JSON response containing the specified info
     * 
     * @param success Whether or not the operation succeeded
     * @param data The data to serialise into JSON
     * @return
     */
    protected ModelAndView generateJsonResponse(boolean success, Object data) {
        ModelMap map = new ModelMap();
        map.put("success", success);
        map.put("data", data);
        return new JSONModelAndView(map);
    }
    
    /**
     * Writes output to input via an in memory buffer of a certain size
     * @param input The input stream
     * @param output The output stream (will receive input's bytes)
     * @param bufferSize The size (in bytes) of the in memory buffer
     * @param closeInput if true, the input will be closed prior to this method returning
     * @throws IOException
     */
    protected void writeInputToOutputStream(InputStream input, OutputStream output, int bufferSize, boolean closeInput) throws IOException {
        try {
            byte[] buffer = new byte[bufferSize];
            int dataRead;
            do {
                dataRead = input.read(buffer, 0, buffer.length);
                if (dataRead > 0) {
                    output.write(buffer, 0, dataRead);
                }
            } while (dataRead != -1);
        } finally {
            if (closeInput) {
                FileIOUtil.closeQuietly(input);
            }
        }
    }
}
